library(plyr)
library(dplyr)
library(memisc)                         #spss.portable.file

load("kff-joint-nogeo-12122018.Rdata")

load("kff_survey_weights_Feb2009_to_Aug2017.RData")

kff_weights$NUMBER <- kff_weights$survey

sdat <- merge(
    sdat,
    kff_weights %>% dplyr::select(-DATE),
    by=c("PSRAID","NUMBER"),
    all.x=T
)

load("kff_survey_weights_Feb2009_to_Mar2019_20200622.RData")

kff_weights$NUMBER <- kff_weights$survey

## left join keeps same order
sdat$WEIGHT_r_and_r <- left_join(
    sdat,
    kff_weights[,c("PSRAID","NUMBER","WEIGHT")],
    by=c("PSRAID","NUMBER"),
    all.x=T
)$WEIGHT.y

sdat <- subset(
    sdat,
    select=c(
        "PSRAID",
        "RETIRED","OTHER","ASIAN","SELFINSURE","EMPLINSURE","MONTH","MARKET",
        "FAVOR","MEDICAID","MEDICARESR","MEDICARE","AGE","COVERED","INCOME",
        "BLACK","HISP","PID","PID5","EDUC","MALE","DATE","DATN","GOP","IND",
        "ST","ACAST","WEIGHT","survey","NUMBER","WEIGHT_r_and_r"
        )
)

save(
    sdat,
    file="data/kff_main_replication_data_with_psraid.RData"
)

sdat <- subset(
    sdat,
    select=c(
        "RETIRED","OTHER","ASIAN","SELFINSURE","EMPLINSURE","MONTH","MARKET",
        "FAVOR","MEDICAID","MEDICARESR","MEDICARE","AGE","COVERED","INCOME",
        "BLACK","HISP","PID","PID5","EDUC","MALE","DATE","DATN","GOP","IND",
        "ST","ACAST","WEIGHT","survey","NUMBER","WEIGHT_r_and_r"
        )
)

save(
    sdat,
    file="data/kff_main_replication_data.RData"
)
